import sys
import random
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QFrame, QSpacerItem,
                             QSizePolicy, QGridLayout)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor, QPalette

# 定义数字到摩斯电码的映射
MORSE_CODE_DICT = {
    '1': '. - - - -', '2': '. . - - -', '3': '. . . - -', '4': '. . . . -',
    '5': '. . . . .', '6': '- . . . .', '7': '- - . . .', '8': '- - - . .',
    '9': '- - - - .', '0': '- - - - -'
}


class NumberGuessingGame(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('数字摩斯电码')
        self.setGeometry(400, 300, 500, 400)

        # 创建布局
        layout = QVBoxLayout()

        # 创建显示摩斯电码的标签
        self.morse_layout = QHBoxLayout()
        layout.addLayout(self.morse_layout)

        # 创建输入区域
        self.input_label = QLabel("输入数字:", self)
        self.input_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.input_label)

        self.user_input = QLabel("", self)
        self.user_input.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.user_input)

        # 创建错误信息标签
        self.error_label = QLabel("", self)
        self.error_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.error_label)

        # 创建小键盘
        keypad_layout = QGridLayout()
        buttons = [
            ('7', 0, 0), ('8', 0, 1), ('9', 0, 2),
            ('4', 1, 0), ('5', 1, 1), ('6', 1, 2),
            ('1', 2, 0), ('2', 2, 1), ('3', 2, 2),
            ('0', 3, 1)
        ]
        for text, row, col in buttons:
            button = QPushButton(text, self)
            button.clicked.connect(lambda _, btn=button: self.append_digit(btn.text()))
            keypad_layout.addWidget(button, row, col)

        clear_button = QPushButton('清除', self)
        clear_button.clicked.connect(self.clear_input)
        keypad_layout.addWidget(clear_button, 3, 0)

        check_button = QPushButton('检查', self)
        check_button.clicked.connect(self.check_answer)
        keypad_layout.addWidget(check_button, 3, 2)

        layout.addLayout(keypad_layout)

        self.setLayout(layout)

        # 初始化游戏
        self.new_game()

    def new_game(self):
        # 生成新的数字
        self.secret_number = self.generate_number()
        # 转换为摩斯电码
        self.morse_code = self.number_to_morse(self.secret_number)
        self.update_morse_display(self.morse_code)
        self.user_input.setText("")
        self.error_label.setText("")

    def generate_number(self):
        # 随机生成3位数到5位数之间的数字
        num_digits = random.randint(3, 4)
        return ''.join([str(random.randint(0, 9)) for _ in range(num_digits)])

    def number_to_morse(self, number):
        # 将数字转换成摩斯电码
        return [MORSE_CODE_DICT[digit] for digit in number]

    def update_morse_display(self, morse_codes):
        # 清除旧的摩斯电码显示
        self.clear_layout(self.morse_layout)

        for code in morse_codes:
            label = QLabel(code, self)
            label.setAlignment(Qt.AlignCenter)
            label.setFrameStyle(QFrame.Box | QFrame.Plain)
            label.setLineWidth(1)
            self.morse_layout.addWidget(label)
            self.morse_layout.addItem(QSpacerItem(10, 10, QSizePolicy.Fixed, QSizePolicy.Minimum))  # 添加间隔

    def append_digit(self, digit):
        current_text = self.user_input.text()
        self.user_input.setText(current_text + digit)

    def clear_input(self):
        self.user_input.setText("")

    def check_answer(self):
        user_guess = self.user_input.text()
        if user_guess == self.secret_number:
            palette = self.error_label.palette()
            palette.setColor(QPalette.WindowText, QColor('green'))
            self.error_label.setPalette(palette)
            self.error_label.setText("答对了！")
            self.new_game()
        else:
            palette = self.error_label.palette()
            palette.setColor(QPalette.WindowText, QColor('red'))
            self.error_label.setPalette(palette)
            self.error_label.setText("答案不对，请再次尝试。")

    def clear_layout(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()  # 安全地删除小部件
                else:
                    self.clear_layout(item.layout())  # 递归清除布局内的布局


if __name__ == '__main__':
    app = QApplication(sys.argv)
    game = NumberGuessingGame()
    game.show()
    sys.exit(app.exec_())
